<template>
  <div>
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="this.$router.back()"
    />
    <van-form @submit="login">
      <van-field
        v-model="mobile"
        name="手机号"
        label="手机号"
        required
        placeholder="手机号"
        :rules="rules.mobile"
      />
      <van-field
        v-model="code"
        type="text"
        name="验证码"
        label="验证码"
        required
        placeholder="验证码"
        :rules="rules.code"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="loading"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { onSubmit } from '@/api/login'
export default {
  name: 'Login',
  data() {
    return {
      mobile: '',
      code: '',
      rules: {
        mobile: [
          {
            required: true,
            message: '请填写手机号'
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式错误'
          }
        ],
        code: [
          {
            required: true,
            message: '请填写验证码'
          },
          {
            pattern: /^\d{6}$/,
            message: '验证码格式错误'
          }
        ]
      },
      loading: false
    }
  },
  computed: {},
  methods: {
    ...mapMutations('user', ['setToken']),
    async login() {
      this.loading = true
      try {
        const res = await onSubmit(this.mobile, this.code)

        this.$toast.success('登陆成功')
        this.setToken(res.data)
        // localStorage.setItem('heima-news-83', JSON.stringify(res.data))
        const back = this.$route.query.back || '/'
        if (back === 'true') {
          this.$router.back()
          return
        }
        this.$router.push(back)
      } catch {
        this.$toast.fail('登陆失败')
      }
      this.loading = false
    }
  }
}
</script>

<style></style>
